package com.study.filter;

import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * LoginFilter 过滤器配置
 * urlPatterns = "/api/*" --- /api 开始的请求将被过滤
 * filterName = "loginFilter" ---- 指定过滤器名称
 *
 * @author huang
 */
@WebFilter(urlPatterns = "/api/*", filterName = "loginFilter")
public class LoginFilter implements Filter {

    /**
     * 项目启动触发
     */
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("过滤器初始化完成...");
    }

    /**
     * 请求被拦截时触发
     * ### 过滤器是有很大的局限性的, 比如不能注入 bean, 只能处理分析下请求参数, 设置字符集等简单操作
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        // 获取请求附带参数, 进行逻辑验证, 决定是否放行
        req.getParameter("username");
        req.getParameter("password");
        String token = req.getParameter("token");

        if (!StringUtils.isEmpty(token)) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 拒绝; 没有返回值, 所以页面不能通过响应做进一步处理, 过滤器适用于非前后分离的项目
            System.out.println("token 不正确");
            // 跳转页面到 index.html
            resp.sendRedirect("/index.html");
        }
    }

    /**
     * 项目停止触发
     */
    @Override
    public void destroy() {
        System.out.println("com.study.filter.LoginFilter destroy...");
    }
}
